package com.techsoul.module.order.controller;

import com.techsoul.common.core.exception.ExcelException;
import com.techsoul.common.core.pojo.Result;
import com.techsoul.common.core.pojo.vo.UserVo;
import com.techsoul.common.core.util.ServletUtils;
import com.techsoul.common.core.util.collection.ListUtils;
import com.techsoul.common.core.util.lang.DateUtils;
import com.techsoul.common.core.util.poi.ExcelImport;
import com.techsoul.common.security.service.TokenService;
import com.techsoul.module.basic.pojo.vo.CustomerVo;
import com.techsoul.module.basic.service.ICustomerService;
import com.techsoul.module.order.enmus.SalesOrderStatusEnum;
import com.techsoul.module.order.pojo.entity.SalesOrder;
import com.techsoul.module.order.pojo.param.SalesOrderItemSaveParam;
import com.techsoul.module.order.pojo.param.SalesOrderItemSearchParam;
import com.techsoul.module.order.pojo.param.SalesOrderSaveParam;
import com.techsoul.module.order.pojo.vo.SalesOrderItemVo;
import com.techsoul.module.order.service.ISalesOrderItemService;
import com.techsoul.module.system.enmus.ErrorType;
import com.techsoul.module.system.pojo.entity.OperationLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.*;

/**
 * 销售订单明细 Controller
 *
 * @author liuen
 * @date 2020-12-09
 */
@Api(tags = "销售订单明细")
@Slf4j
@RestController
@RequestMapping("/order/salesOrderItem")
public class SalesOrderItemController {

    @Autowired
    private Result result;
    
    @Autowired
    private ISalesOrderItemService service;
    @Autowired
    private TokenService tokenService;

    @Autowired
    private ICustomerService iCustomerService;

    @ApiOperation("新增")
    @PreAuthorize("hasAnyAuthority('order:salesOrder:insert')")
    @PostMapping
    public Result insert(@Valid @RequestBody SalesOrderItemSaveParam params) {
        return result.success(this.service.insert(params));
    }

    @ApiOperation("批量删除（多个用逗号隔开）")
    @PreAuthorize("hasAnyAuthority('order:salesOrder:delete')")
    @DeleteMapping("/{ids}")
    public Result batchDelete(@PathVariable String[] ids) {
        this.service.batchDelete(Arrays.asList(ids));
        return result.success();
    }

    @ApiOperation("修改")
    @PreAuthorize("hasAnyAuthority('order:salesOrder:update')")
    @PutMapping("/{id}")
    public Result update(@PathVariable String id, @Valid @RequestBody SalesOrderItemSaveParam params) {
        return result.success(this.service.update(id, params));
    }

    @ApiOperation("修复数据")
    @PreAuthorize("hasAnyAuthority('order:salesOrder:update')")
    @PostMapping("/fixdata")
    public Result fixdata(@RequestBody SalesOrderItemSaveParam params) {
        this.service.fixdata();
        return result.success();
    }

    @ApiOperation("再次导入")
    @PreAuthorize("hasAnyAuthority('order:salesOrder:update')")
    @PutMapping("/importAgain/{id}")
    public Result importAgain(@PathVariable String id) {
        return result.success(this.service.importAgain(id));
    }


    @ApiOperation("详情")
    @PreAuthorize("hasAnyAuthority('order:salesOrder:search')")
    @GetMapping("/{id}")
    public Result findById(@PathVariable("id") String id) {
        return result.success(this.service.findById(id));
    }

    @ApiOperation("列表")
    @PreAuthorize("hasAnyAuthority('order:salesOrder:search')")
    @PostMapping("/search")
    public Result findAll(@RequestBody SalesOrderItemSearchParam params) {
        return result.success(this.service.findAll(params));
    }

   /* @ApiOperation("品牌排行列表-分页")
    @PostMapping("/brandRateView/{current}/{pageSize}")
    public Result brandRateView(@RequestBody SalesOrderItemSearchParam params, @PathVariable Integer current, @PathVariable Integer pageSize) {
        return result.success(this.service.brandRateView(params, current, pageSize));
    }
    @ApiOperation("供应商排行列表-分页")
    @PostMapping("/supplierRateView/{current}/{pageSize}")
    public Result supplierRateView(@RequestBody SalesOrderItemSearchParam params, @PathVariable Integer current, @PathVariable Integer pageSize) {
        return result.success(this.service.supplierRateView(params, current, pageSize));
    }*/
    @ApiOperation("列表-分页")
    @PreAuthorize("hasAnyAuthority('order:salesOrder:search')")
    @PostMapping("/search/{current}/{pageSize}")
    public Result findAll(@RequestBody SalesOrderItemSearchParam params, @PathVariable Integer current, @PathVariable Integer pageSize) {
        return result.success(this.service.findAll(params, current, pageSize));
    }

    @ApiOperation("导入模板")
    @PreAuthorize("hasAnyAuthority('order:salesOrder:insert')")
    @PostMapping("/importTemplate")
    public Result importTemplate() {
        return result.success(this.service.importTemplate());
    }
    @ApiOperation("历史数据导入")
    @PreAuthorize("hasAnyAuthority('order:salesOrder:search')")
    @PostMapping("/dataMigration")
    public Result dataMigration(String customerNo, MultipartFile file) {
        return result.success(this.service.dataMigration(customerNo, file));
    }
    @ApiOperation("导入")
    @PreAuthorize("hasAnyAuthority('order:salesOrder:insert')")
    @PostMapping("/importData")
    public Result importData(String customerNo, MultipartFile file) {
        List<SalesOrderItemVo> dataList = null;
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        CustomerVo customerVo = iCustomerService.findById(customerNo);

        int successNum = 0;
        int failureNum = 0;
        int logNum = 0;
        try {
            ExcelImport excelImport = new ExcelImport(file, 1, 0);
            dataList = excelImport.getDataList(SalesOrderItemVo.class);
        } catch (Exception e) {
            log.error("获取数据信息失败!");
            throw new ExcelException("获取数据信息失败!");
        }
        if (ListUtils.isEmpty(dataList)) {
            throw new ExcelException("导入数据不能为空！");
        }

        if(dataList==null||dataList.size()==0){
            //return "没有读取到数据";
            log.error("没有读取到数据!");
        }
        SalesOrderItemVo firstdata = (SalesOrderItemVo)dataList.get(0);
        String custOrderNo ="";
        SalesOrder newSalesOrder = null;
        int itemNo = 0;
        int line = 0;
        List<String> custOrderNos = new ArrayList<String>();
        for (SalesOrderItemVo data : dataList) {
            successNum++;
            line++;
            // if(!data.getCustSalesOrderNo().equals(custOrderNo)){
            custOrderNo = data.getCustSalesOrderNo();
            if (!custOrderNos.contains(custOrderNo)) {
                newSalesOrder=   this.service.importData(customerNo, data,custOrderNo,user,itemNo,line, customerVo,newSalesOrder);
                custOrderNo = data.getCustSalesOrderNo();
                custOrderNos.add(custOrderNo);
            }else{
                newSalesOrder=this.service.importData(customerNo, data,"No",user,itemNo,line,customerVo,newSalesOrder);
            }
            itemNo = itemNo++;
        }
       /* if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误清查日志");
            OperationLog operationLog =new OperationLog();
            operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatusName());
            operationLog.setErrorMsg(failureMsg.toString());
            operationLog.setMethod("导入模板-原始订单-批量导入");
            operationLog.setLocation("第"+line+"行");
            operationLog.setId(idWorker.nextId() + "").preInsert(user.getId());
            if (user != null) {
                operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
            }
            operationLogMapper.insert(operationLog);
            // throw new ExcelException(failureMsg.toString());

            return result.success("操作有"+failureNum+"行输入异常，请看日志");
        } else {*/
          //  if(logNum>0){
        //        successMsg.insert(0, "恭喜您，操作成功！共 " + successNum + " 条，另有：" +logNum+ " 条数据不能正常导入，已写入日志");

          //  }else{
                successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");

        //    }
       // }
        return result.success(successMsg.toString());
    }

    @ApiOperation("队列读取数据")
    @PreAuthorize("hasAnyAuthority('order:salesOrder:search')")
    @PostMapping("/readMq")
    public Result readMq(@RequestBody SalesOrderSaveParam params) {
        this.service.readMq(params);
        return result.success();
    }

    @ApiOperation("订单总数-按区域查询")
    @PreAuthorize("hasAnyAuthority('order:salesOrder:search')")
    @PostMapping("/findTotalOrder")
    public Result findTotalOrder() {
        UserVo sysuser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        return result.success(this.service.findTotalOrder(sysuser.getSite()));
    }
    @ApiOperation("订单总数-按区域查询")
    @PreAuthorize("hasAnyAuthority('order:salesOrder:search')")
    @PostMapping("/findTotalTodayOrder")
    public Result findTotalTodayOrder() {
        UserVo sysuser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        SalesOrderItemSearchParam salesOrderItemSearchParam = new SalesOrderItemSearchParam();
        Date today = new Date();
        String datestr = DateUtils.formatDate(today);
        datestr = datestr.concat(" ").concat("00:00:00");
        salesOrderItemSearchParam.setOrderTime(datestr);
        return result.success(this.service.findTotalTodayOrder(salesOrderItemSearchParam));
    }

    @ApiOperation("销售金额汇总-按区域查询")
    @PreAuthorize("hasAnyAuthority('order:salesOrder:search')")
    @PostMapping("/countTotalPurchase")
    public Result countTotalPurchase() {
        UserVo sysuser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        SalesOrderItemSearchParam salesOrderItemSearchParam = new SalesOrderItemSearchParam();
        String year =  DateUtils.getYear();
        String mon = DateUtils.getMonth();

        String thismon = year.concat("-").concat(mon);
        salesOrderItemSearchParam.setJobDate(thismon);
        return result.success(this.service.countTotalPurchase(salesOrderItemSearchParam));
    }
    @ApiOperation("销售金额汇总-按区域查询")
    @PreAuthorize("hasAnyAuthority('order:salesOrder:search')")
    @PostMapping("/countTotalSale")
    public Result countTotalSale() {
        UserVo sysuser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        SalesOrderItemSearchParam salesOrderItemSearchParam = new SalesOrderItemSearchParam();
        String year =  DateUtils.getYear();
        String mon = DateUtils.getMonth();

        String thismon = year.concat("-").concat(mon);
        salesOrderItemSearchParam.setJobDate(thismon);
        return result.success(this.service.countTotalSale(salesOrderItemSearchParam));
    }

    @ApiOperation("登记退单")
    @PreAuthorize("hasAnyAuthority('order:salesOrder:insert')")
    @PostMapping("/createReturn")
    public Result createReturn(@RequestBody SalesOrderItemSaveParam params) {

        String ret = service.createReturn(params);
        return result.success();

    }
    @ApiOperation("单品销售排行列表-分页")
    @PreAuthorize("hasAnyAuthority('order:salesOrder:search')")
    @PostMapping("/skuRateView/{current}/{pageSize}")
    public Result skuRateView(@RequestBody SalesOrderItemSearchParam params, @PathVariable Integer current, @PathVariable Integer pageSize) {
        return result.success(this.service.skuRateView(params, current, pageSize));
    }
    @ApiOperation("供应商-查询新订单")
    @PreAuthorize("hasAnyAuthority('order:salesOrder:suppier')")
    @PostMapping("api/suppierViewNewOrder")
    public Result suppierViewNewOrder(@RequestBody Map map){
        String supplierNo = (String) map.get("supplierNo");
        SalesOrderItemSearchParam salesOrderItemSearchParam =new SalesOrderItemSearchParam();
        List<SalesOrderItemVo> retresult = this.service.findAll(salesOrderItemSearchParam);
        salesOrderItemSearchParam.setSupplierNo(supplierNo);
        salesOrderItemSearchParam.setSupplierStatus(SalesOrderStatusEnum.CREATED.getValue());
        return result.success(retresult);
    }

    @ApiOperation("供应商-报告已出发")
    @PreAuthorize("hasAnyAuthority('order:salesOrder:suppier')")
    @PostMapping("api/suppierReportDepart")
    public Result suppierReportDepart(@RequestBody Map map){
       String rt =  this.service.suppierReportDepart(map);
        return result.success(rt);
    }
    @ApiOperation("供应商-查询时间段自己订单")
    @PreAuthorize("hasAnyAuthority('order:salesOrder:suppier')")
    @PostMapping("api/suppierViewMyOrder")
    public Result suppierViewMyOrder(@RequestBody Map map){
        String supplierNo = (String) map.get("supplierNo");
        String dateFrom = (String) map.get("dateFrom");
        String dateTo = (String) map.get("dateTo");
        SalesOrderItemSearchParam salesOrderItemSearchParam =new SalesOrderItemSearchParam();
        salesOrderItemSearchParam.setSupplierNo(supplierNo);
        salesOrderItemSearchParam.setCreateTimeBegin(dateFrom);
        salesOrderItemSearchParam.setCreateTimeEnd(dateTo);
        List<SalesOrderItemVo> retresult = this.service.findAll(salesOrderItemSearchParam);

        return result.success(retresult);
    }
    @ApiOperation("导出")
    @PreAuthorize("hasAnyAuthority('order:salesOrder:search')")
    @PostMapping("/exportData")
    public Result exportData(@RequestBody SalesOrderItemSearchParam params) {
        return result.success(this.service.exportData(params));
    }
}
